package com.apes.fn.server.productRequireManage.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productRequireManage.model.ReplenishmentBusinessImpAbstract;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.stock.transfer.model.Transfer;
import com.apes.scm.stock.transfer.repository.TransferRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;


@Service("repleDumpOrderService")
public class RepleDumpOrderService extends ReplenishmentBusinessImpAbstract {

    @Autowired
    private LocationRepository locationRepository;
    @Autowired
    private TransferRepository transferRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;

    @Override
    public Map sendOrder(JSONObject getJO) {
        JSONObject fLocationObj = getJO.getJSONObject("location");
        Location fLocation = locationRepository.findOne(fLocationObj.getString("id"));

        // 根据要货仓库补货，此处分组
        Map<JSONObject, List<Object>> groupRequires = getJO.getJSONArray("item").stream().collect(Collectors.groupingBy(item -> {
            JSONObject itemObj = (JSONObject) item;
            String customerExpandId = Objects.isNull(itemObj.get("customerExpand"))?"":itemObj.getJSONObject("customerExpand").getString("id");
            JSONObject group = new JSONObject(MapUtil.mapper("locationId", itemObj.getJSONObject("location").getString("id"), "customerExpandId", customerExpandId));
            return group;
        }));

        // 分组后循环配货
        AtomicReference dumpIdStr = new AtomicReference(" ");
        groupRequires.forEach((k, items) -> {
            Location cLocation = locationRepository.findOne(k.getString("locationId"));
            JSONArray itemArray = new JSONArray();
            itemArray.addAll(items);

            // 发送转储请求 -- 考虑自己建一个事务？
            if (fLocation.getCompany().getId().equals(cLocation.getCompany().getId())) {
                Set<Map> dumpItems = this.appendCrossCompanyTransferItem(itemArray, fLocation, cLocation);
                if (dumpItems.isEmpty()) return;
                Map transferM = this.appendTransferData(fLocation, cLocation, dumpItems);
                transferM.put("customerExpandId", k.getString("customerExpandId"));

                Transfer transfer = invoke("stock.transfer.autoRequireTransfer", transferM);
                transfer = transferRepository.findOne(transfer.getId());
                transfer.setApproveUid(transfer.getCreateUid());

                transfer.setBatchRequireId(getJO.getString("allRequireId"));
                Transfer tf = invoke("stock.transfer.approve", transfer);
                dumpIdStr.set(dumpIdStr.get() + tf.getId() + "\r\n");

            } else {
                String reception = invoke("scm.transferProductService.accordLCompanyChangeOperation", MapUtil.mapper("id", cLocation.getId()));
                Set<Map> dumpItems = this.appendCrossCompanyTransferItem(itemArray, fLocation, cLocation);
                if (dumpItems.isEmpty()) return;
                Map cross = this.appendCrossMain(fLocation, cLocation, reception);
                cross.put("crossCompanyTransferItems", dumpItems);
                cross.put("batchRequireId", getJO.get("allRequireId"));
                if (StringUtils.hasText(k.getString("customerExpandId"))) cross.put("customerExpand", MapUtil.mapper("id", k.getString("customerExpandId")));

                String dumpId = invoke("cross.crossCompanyTransferNewService.safetyGapCreateCross", cross);
                dumpIdStr.set(dumpIdStr.get() + dumpId + "、\r\n");
            }
        });
        return MapUtil.mapper("orderId", dumpIdStr.get());
    }

    // 拼接跨公司主数据
    private Map appendCrossMain(Location fLocation, Location subLocation, String reception) {
        PartyRole operator = partyRoleRepository.findOne("system");
        List<User> userInfo = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", operator.getId()));
        Map crossTransfer = new HashMap();
        crossTransfer.put("creator", operator.getId());
        crossTransfer.put("createUid", MapUtil.mapper("id", operator.getId(), "name", operator.getName()));
        crossTransfer.put("userId", userInfo.get(0).getId().toString());
        crossTransfer.put("sourceBusinessType", "ProductRequire");
        crossTransfer.put("company", MapUtil.mapper("id", subLocation.getCompany().getId()));
        crossTransfer.put("shipLocation", MapUtil.mapper("id", fLocation.getId()));
        crossTransfer.put("receiptLocation", MapUtil.mapper("id", subLocation.getId()));
        crossTransfer.put("returnReason", MapUtil.mapper("id", "000180"));
        crossTransfer.put("state", "sent");
        crossTransfer.put("note", "要货补货管理转储");
        crossTransfer.put("isAuto", true);
        crossTransfer.put("specialDocumentsType", "要货补货转储新逻辑 - 后面要剔除"); // 固定并使用

        String export = invoke("scm.transferProductService.accordLCompanyChangeOperation", MapUtil.mapper("id", fLocation.getId()));
        List<String> supplierIds = invoke("scm.transferProductService.accordOperationFindSupplier", MapUtil.mapper("export", export, "reception", reception));
        List<String> handleSupplierIds = supplierIds.contains("existsSupplierNull")?new ArrayList<>():supplierIds;
        if ("001073".equals(export) && !"001073".equals(reception)) {
            crossTransfer.put("existsTransferProductSupplierIsNull", supplierIds.contains("existsSupplierNull"));
            crossTransfer.put("transferProductSuppliers", handleSupplierIds);
            crossTransfer.put("empowermentToNoEmpowerment", true);
        } else {
            crossTransfer.put("existsTransferProductSupplierIsNull", supplierIds.contains("existsSupplierNull"));
            crossTransfer.put("transferProductSuppliers", handleSupplierIds);
        }

        return crossTransfer;
    }

    /** 拼接跨公司调拨明细 */
    private Set<Map> appendCrossCompanyTransferItem(JSONArray requiredItems, Location fLocation, Location subLocation) {

        Set<Map> dumpItems = new HashSet<>();
        requiredItems.forEach(requireItems -> {
            JSONObject itemObj = (JSONObject) requireItems;
            double gapQty = itemObj.getDoubleValue("distributionQty");

            String productId = itemObj.getJSONObject("product").getString("id");
            String reception = invoke("scm.transferProductService.accordLCompanyChangeOperation", MapUtil.mapper("id", subLocation.getId()));
            double usableQty = this.obtainStockUsableQty(reception, fLocation.getId(), productId, subLocation.getCompany().getId());
            double transferQty = usableQty >= gapQty?gapQty:gapQty > usableQty?usableQty:0;



            String dumpUomId = itemObj.getJSONObject("uom").getString("id");
            if (fLocation.getCompany().getId().equals(subLocation.getCompany().getId())) { // 怎么将这个条件解耦??????????????????????
                dumpItems.add(
                        MapUtil.mapper("product", MapUtil.mapper("id", productId),
                                "uom", MapUtil.mapper("id", dumpUomId),
                                "transferQty", transferQty));
            } else {
                dumpItems.add(
                        MapUtil.mapper("product", MapUtil.mapper("id", productId),
                                "uom", MapUtil.mapper("id", dumpUomId),
                                "productSumQty", usableQty,
                                "productSum", transferQty));
            }

        });
        return dumpItems;
    }

    // 拼接转储主表
    private Map appendTransferData(Location fLocation, Location cLocation, Set<Map> transferItems) {
        Map transfer = new HashMap();
        PartyRole operatorName = partyRoleRepository.findOne("system");
        List<User> userInfo = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", operatorName.getId()));
        transfer.put("creator", operatorName.getId());
        transfer.put("createUid", MapUtil.mapper("id", operatorName.getId(), "name", operatorName.getName()));
        transfer.put("userId", userInfo.get(0).getId());
        transfer.put("specialDocuments", DateUtil.format(DateUtil.SHOW_DATE_FORMAT));
        transfer.put("sourceBusinessType", "ProductRequire");
        transfer.put("scene", MapUtil.mapper("id", "PT001"));
        transfer.put("originLocation", MapUtil.mapper("id", fLocation.getId(), "name", fLocation.getName()));
        transfer.put("receiptLocation", MapUtil.mapper("id", cLocation.getId(), "name", cLocation.getName()));
        transfer.put("company", MapUtil.mapper("id", cLocation.getCompany().getId()));
        transfer.put("note", "要货补货管理转储");
        transfer.put("reason", MapUtil.mapper("id", "000180"));
        transfer.put("state", "sent");
        transfer.put("transferType", MapUtil.mapper("id", "000165"));
        transfer.put("specialDocumentsType", "要货补货转储新逻辑 - 后面要剔除"); // 固定并使用
        transfer.put("transferItems", transferItems);

        return transfer;
    }


}





















